package controllers.data.test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import models.Target;

import com.hp.hpl.jena.query.QuerySolution;

import controllers.data.providers.Sparql;


public class BuildTable
{

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException
    {
        BuildTable.sameAs("foaf:Person");
    }


    public static void sameAs(String type) throws IOException
    {
        BufferedWriter out = new BufferedWriter(new FileWriter("data/person_sameas.csv"));

        List<QuerySolution> instances = Sparql.query("SELECT distinct ?a {?a ?c " + type + "}", Target.DBPEDIA);

        for(QuerySolution instance : instances) {
            String name = instance.getResource("?a").toString();

            List<QuerySolution> relations = Sparql.query("SELECT distinct ?c {<" + name + "> owl:sameAs ?c}", Target.DBPEDIA);

            for(QuerySolution relation : relations) {
                String uri = relation.get("?c").toString();

                if(uri.contains("freebase")) {
                    @SuppressWarnings ("deprecation")
                    String dbpedia = URLDecoder.decode(name);
                    String freebase = uri.substring(uri.lastIndexOf("/")).replace(".", "/");

                    out.write(dbpedia + ";" + freebase + System.getProperty("line.separator"));
                }
            }
        }

        out.close();
    }
}